package com.tticar.invmanager.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.tticar.invmanager.common.exception.MyServiceException;
import com.tticar.invmanager.entity.*;
import com.tticar.invmanager.entity.vo.MyPage;
import com.tticar.invmanager.entity.vo.RepositoryCountSearchDto;
import com.tticar.invmanager.mapper.RepositoryCountMapper;
import com.tticar.invmanager.service.*;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 商品库存数量表 服务实现类
 * </p>
 *
 * @author joeyYan
 * @since 2018-08-10
 */
@Service
public class RepositoryCountServiceImpl extends ServiceImpl<RepositoryCountMapper, RepositoryCount> implements IRepositoryCountService {

    @Autowired
    private IMMaterielSkuService materielSkuService;
    @Autowired
    private RepositoryCountMapper repositoryCountMapper;
    @Autowired
    private IMCateogryService cateogryService;

    @Override
    public Page selectPage(RepositoryCountSearchDto searchDto, MyPage<RepositoryCount> page) {
        if (searchDto.getCategoryId() != null) {
            Wrapper wrapper = new EntityWrapper<>();
            wrapper.eq("status", 0);
            wrapper.eq("pid", searchDto.getCategoryId());
            List<MCateogry> mCateogries = cateogryService.selectList(wrapper);
            String categoryIds = searchDto.getCategoryId() + ",";
            if (mCateogries != null && mCateogries.size() > 0) {
                for (MCateogry mCateogry : mCateogries) {
                    categoryIds = categoryIds + mCateogry.getId() + ",";
                }
            }
            categoryIds = categoryIds.substring(0, categoryIds.length() - 1);
            searchDto.setCategoryList(categoryIds);
        }
        List<Map> search = this.baseMapper.search(searchDto, page);

        return page.setRecords(this.baseMapper.search(searchDto, page));
    }

    @Override
    public List<RepositoryCount> selectDetailAll(long houseId, List<Long> skuIdList) {
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq(RepositoryCount.WEARHOUSE_ID, houseId);
        wrapper.in(CollectionUtils.isNotEmpty(skuIdList), RepositoryCount.SKU_ID, skuIdList);
        List<RepositoryCount> countList = this.selectList(wrapper);

        List<MMaterielSku> skuList = null;
        List<Long> skuIds = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(countList)) {
            for (RepositoryCount count : countList) {
                skuIds.add(count.getSkuId());
            }
        } else {
            return null;
        }
        if (CollectionUtils.isNotEmpty(skuIds)) {
            skuList = materielSkuService.selectBatchIds(skuIds);
        }
//        if (CollectionUtils.isNotEmpty(skuList)) {
//            for (RepositoryCount count : countList) {
//                WWearhouse wearhouse = wearhouseService.selectById(count.getWearhouseId());
//                WPosition position = positionService.selectById(count.getPositionId());
//                count.setHouseName(wearhouse == null ? "" : wearhouse.getName());
//                count.setPositionName(position == null ? "" : position.getName());
//                for (MMaterielSku sku : skuList) {
//                    if (count.getSkuId().equals(sku.getId())) {
//                        count.setSkus(sku.getSkus());
//                        MMateriel mMateriel = materielService.selectById(sku.getMid());
//                        if (mMateriel != null) {
//                            count.setMaterielName(mMateriel.getName());
//                            count.setMaterielCode(mMateriel.getCode());
//                        }
//                        break;
//                    }
//                }
//            }
//        }
        return countList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> ids) {
        List list = new ArrayList();
        for (Long id : ids) {
            RepositoryCount repositoryCount = new RepositoryCount();
            repositoryCount.setId(id);

            list.add(repositoryCount);
        }
        this.updateBatchById(list);
    }

    @Override
    public RepositoryCount selectDataBySkuIdAndWearhouseId(Long skuId, Long wearhouseId) {
        if (skuId == null || wearhouseId == null) {
            throw new MyServiceException("参数不能为空");
        }
        return baseMapper.selectDataBySkuIdAndWearhouseId(skuId, wearhouseId);
    }

    @Override
    public RepositoryCount selectDataBySkuIdAndWearhouseIdByTenantId(Long skuId, Long wearhouseId,Long tenantId) {
        if (skuId == null || wearhouseId == null || tenantId == null) {
            throw new MyServiceException("参数不能为空");
        }
        return baseMapper.selectDataBySkuIdAndWearhouseIdByTenantId(skuId, wearhouseId,tenantId);
    }

    @Override
    public RepositoryCount selectDataBySkuIdAndWearhouseIdAndPositionId(Long skuId, Long wearhouseId, Long positionId) {
        if (skuId == null || wearhouseId == null || positionId == null) {
            throw new MyServiceException("参数不能为空");
        }
        return baseMapper.selectDataBySkuIdAndWearhouseIdAndPositionId(skuId, wearhouseId, positionId);
    }


    @Override
    public RepositoryCount selectDataBySkuIdAndWearhouseIdAndPositionIdAndTenantId(Long skuId, Long wearhouseId, Long positionId,Long tenantId) {
        if (skuId == null || wearhouseId == null || positionId == null) {
            throw new MyServiceException("参数不能为空");
        }
        return baseMapper.selectDataBySkuIdAndWearhouseIdAndPositionIdAndTenantId(skuId, wearhouseId, positionId,tenantId);
    }

    @Override
    public List<Map> getSkuNum(String skuIds) {
        return baseMapper.getSkuNum(skuIds);
    }

    @Override
    public List<Map> getSkuNumByHouseId(String skuIds, Long houseId) {
        Map<String, Object> map = new HashMap<>();
        map.put("skuIds", skuIds);
        map.put("houseId", houseId);
        return this.baseMapper.getSkuNumByHouseId(map);
    }

    /**
     * 出入库的同时进行库存量加减
     * 参数count：为正数的时候是入库，数量加；为负数是出库，数量减  弃用库位，批次版本
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRepositoryCount(Long skuId, Long wearhouseId, Integer count) {
        RepositoryCount repositoryCount = selectDataBySkuIdAndWearhouseId(skuId, wearhouseId);
        if (count > 0 && repositoryCount == null) {
            repositoryCount = new RepositoryCount();
            repositoryCount.setCount(count);
            repositoryCount.setSkuId(skuId);
            repositoryCount.setWearhouseId(wearhouseId);
            insert(repositoryCount);
        } else if (count > 0 && repositoryCount != null) {
            repositoryCount.setCount(repositoryCount.getCount() + count);
            updateById(repositoryCount);
        } else if (count < 0) {
            if (repositoryCount == null || repositoryCount.getCount() + count < 0) {
                throw new MyServiceException("货物库存不足！");
            } else {
                repositoryCount.setCount(repositoryCount.getCount() + count);
                updateById(repositoryCount);
            }

        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRepositoryCountByTenantId(Long skuId, Long wearhouseId, Integer count,Long tenantId) {
        RepositoryCount repositoryCount = selectDataBySkuIdAndWearhouseIdByTenantId(skuId, wearhouseId,tenantId);
        repositoryCount.setTenantId(tenantId);
        if (count > 0 && repositoryCount == null) {
            repositoryCount = new RepositoryCount();
            repositoryCount.setCount(count);
            repositoryCount.setSkuId(skuId);
            repositoryCount.setWearhouseId(wearhouseId);
            repositoryCount.setTenantId(tenantId);
            insert(repositoryCount);
        } else if (count > 0 && repositoryCount != null) {
            repositoryCount.setCount(repositoryCount.getCount() + count);
            updateById(repositoryCount);
        } else if (count < 0) {
            if (repositoryCount == null || repositoryCount.getCount() + count < 0) {
                throw new MyServiceException("货物库存不足！");
            } else {
                repositoryCount.setCount(repositoryCount.getCount() + count);
                updateById(repositoryCount);
            }

        }
    }


    /**
     * 出入库的同时进行库存量加减
     * 参数count：为正数的时候是入库，数量加；为负数是出库，数量减
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRepositoryCountByPositionId(Long skuId, Long wearhouseId, Long positionId, Integer count) {
        RepositoryCount repositoryCount = selectDataBySkuIdAndWearhouseIdAndPositionId(skuId, wearhouseId, positionId);
        if (count > 0 && repositoryCount == null) {
            repositoryCount = new RepositoryCount();
            repositoryCount.setCount(count);
            repositoryCount.setSkuId(skuId);
            repositoryCount.setWearhouseId(wearhouseId);
            repositoryCount.setPositionId(positionId);
            insert(repositoryCount);
        } else if (count > 0 && repositoryCount != null) {
            repositoryCount.setCount(repositoryCount.getCount() + count);
            updateById(repositoryCount);
        } else if (count < 0) {
            if (repositoryCount == null || repositoryCount.getCount() + count < 0) {
                throw new MyServiceException("货物库存不足！");
            } else {
                repositoryCount.setCount(repositoryCount.getCount() + count);
                updateById(repositoryCount);
            }

        }

    }


    /**
     * 其他端发货允许扣为负库存 new version 不可为负库存
     * */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRepositoryCountByPositionIdAndTenantId(Long skuId, Long wearhouseId, Long positionId, Integer count,Long tenantId) {
        RepositoryCount repositoryCount = selectDataBySkuIdAndWearhouseIdAndPositionIdAndTenantId(skuId, wearhouseId, positionId,tenantId);
        repositoryCount.setTenantId(tenantId);
        if (count > 0 && repositoryCount == null) {
            repositoryCount = new RepositoryCount();
            repositoryCount.setCount(count);
            repositoryCount.setSkuId(skuId);
            repositoryCount.setWearhouseId(wearhouseId);
            repositoryCount.setPositionId(positionId);

            insert(repositoryCount);
        } else if (count > 0 && repositoryCount != null) {
            repositoryCount.setCount(repositoryCount.getCount() + count);
            updateById(repositoryCount);
        } else if (count < 0) {
            if (repositoryCount == null || repositoryCount.getCount() + count < 0) {
                throw new MyServiceException("货物库存不足！");
            } else {
                repositoryCount.setCount(repositoryCount.getCount() + count);
                updateById(repositoryCount);
            }

        }

    }
    /**
     * 先出默认仓库，再出其他
     * */
    @Override
    public List<RepositoryCount> queryOutRepository(Long skuId) {
        List<RepositoryCount> repositoryCounts = repositoryCountMapper.firstOutDefaultRepository(skuId);
        List<RepositoryCount> repositoryCounts1 = repositoryCountMapper.nextOutAnother(skuId);
        for (int i = 0;i< repositoryCounts1.size();i++) {
            if (repositoryCounts1.get(i).getWearhouseId().equals(repositoryCounts.get(0).getWearhouseId())) {
                repositoryCounts1.remove(i);
                break;
            }
        }
        repositoryCounts.addAll(repositoryCounts1);
        return repositoryCounts;
    }

    @Override
    public List<RepositoryCount> queryOutRepositoryByTenantId(Long skuId,Long tenantId) {
        List<RepositoryCount> repositoryCounts = repositoryCountMapper.firstOutDefaultRepositoryByTenantId(skuId,tenantId);
        List<RepositoryCount> repositoryCounts1 = repositoryCountMapper.nextOutAnotherByTenantId(skuId,tenantId);
        for (int i = 0;i< repositoryCounts1.size();i++) {
            if (repositoryCounts1.get(i).getWearhouseId().equals(repositoryCounts.get(0).getWearhouseId())) {
                repositoryCounts1.remove(i);
                break;
            }
        }
        repositoryCounts.addAll(repositoryCounts1);
        return repositoryCounts;
    }

    @Override
    public List<RepositoryCount> queryOutRepositoryByHouseId(Long skuId,Long houseId) {
        return repositoryCountMapper.queryOutRepositoryByHouseId(skuId,houseId);

    }

    @Override
    public List<Map> getRepositoryListByStoreId(Long storeId) {
        Long tenantId = repositoryCountMapper.selectTenantIdByStoreId(storeId);
        if (tenantId == null) {
            throw new MyServiceException("该店铺未关联仓储");
        }
        return repositoryCountMapper.selectRepositoryListByTenantId(tenantId);
    }

    @Override
    public Map queryGoodsMessageForSupplierApp(Long storeId, Long repositoryId, String searchText,Long page,Long pageSize) {
        Long tenantId = repositoryCountMapper.selectTenantIdByStoreId(storeId);
        if (tenantId == null) {
            throw new MyServiceException("该店铺未关联仓储");
        }
        List<Long> repositoryList = new ArrayList<>();
        if (repositoryId == null) {
            List<Map> repositoryListByStoreId = getRepositoryListByStoreId(storeId);
            for (int i = 0;i < repositoryListByStoreId.size(); i++) {
                repositoryList.add(Long.valueOf(repositoryListByStoreId.get(i).get("id").toString()));
            }
        } else {
            repositoryList.add(repositoryId);
        }
        Map<String,Object> map = new HashMap<>(8);
        map.put("searchText", searchText);
        map.put("repositoryList", repositoryList);
        map.put("tenantId", tenantId);
        map.put("start", (page - 1) * pageSize);
        map.put("size", pageSize);
        List<Map> repositoryListByStoreId = repositoryCountMapper.queryGoodsMessageForSupplierApp(map);
        List<Map> count = repositoryCountMapper.queryCount(map);
        int total = count.size();
        int totalPageNum = (total  +  pageSize.intValue()  - 1) / pageSize.intValue();
        Map resultMap = new HashMap<>(4);
        resultMap.put("dataList",repositoryListByStoreId );
        resultMap.put("total", total);
        resultMap.put("pages", totalPageNum);
        return resultMap;

    }
}
